package com.defysoft.waukids.main;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukids.BaseActivity;
import com.defysoft.waukids.Custom_Data_Type.WK_MEMBERSTUDENT_CONNECT_LOAD;
import com.defysoft.waukids.Data_Sharedpreferences;
import com.defysoft.waukids.JsonParser;
import com.defysoft.waukids.PublicSharedpreferences;
import com.defysoft.waukids.R;
import com.defysoft.waukids.Sqlite_Connect;

public class Main_MemberStudent_Connect_A extends BaseActivity implements OnClickListener{
	String PK_Stu_Code, PK_Mem_Email;
	TextView tv[] = new TextView[2];
	EditText et;
	WK_MEMBERSTUDENT_CONNECT_LOAD bc_Student_Che;
	boolean checkStudent = false;			//자녀코드확인 버튼 눌렀는지 확인.
	private final int SEARCH_CODE = 10;		//자녀코드 자녀매칭 확인
	private final int INSERT_CODE = 9;		//자녀코드 입력
	private final int SEARCH_SUCCESS = 8;		//코드검색 성공
	private final int SEARCH_FAILURE = 7;		//코드검색 실패
	private final int INSERT_SUCCESS = 6;		//자녀코드 입력
	private final int INSERT_FAILURE = 5;		//자녀코드 입력
	
	Toolbar toolbar;
	public Sqlite_Connect sqlite_Connect;
	PublicSharedpreferences psf;
	Data_Sharedpreferences.SF_Member member;
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		PK_Mem_Email = getIntent().getStringExtra("PK_Mem_Email");
		setContentView(R.layout.member_memberstudent_connect_a);
		setStartToolbar();
		setStartData();
	}
	
	@Override
	public void setStartData() {
		super.setStartData();
		sqlite_Connect = new Sqlite_Connect(this);
		psf = new PublicSharedpreferences(this);
		psf.setMembersp();
		member = psf.getMembersp();
		PK_Stu_Code = getIntent().getStringExtra("PK_Stu_Code");
		tv[0] = (TextView)findViewById(R.id.MAIN_MEMBERSTUDENT_CONNECT_MATCHCHECK);	//자녀코드 확인
		tv[1] = (TextView)findViewById(R.id.MAIN_MEMBERSTUDENT_CONNECT_BTN);			//자녀등록 버튼
		tv[0].setOnClickListener(this);
		tv[1].setOnClickListener(this);
		et = (EditText)findViewById(R.id.MAIN_MEMBERSTUDENT_CONNECT_NAME);			//자녀코드.
		checkStudent = false;

		
		//코드확인 뒤 수정하면 다시 확인.
		et.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				checkStudent  = false;
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}
			@Override
			public void afterTextChanged(Editable s) {
				
			}
		});
	}
	
	private void setStartToolbar() {
		toolbar = (Toolbar) findViewById(R.id.MAIN_MEMBERSTUDENT_CONNECT_TOOL);
		toolbar.setNavigationOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		/*spinner.setVisibility(View.VISIBLE);*/
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.MAIN_MEMBERSTUDENT_CONNECT_MATCHCHECK:
			if (et.getText().length() == 0) {
				Toast.makeText(this, "자녀코드를 입력하세요.", Toast.LENGTH_LONG).show();
			} else if(et.getText().length() != 8){
				Toast.makeText(this, "자녀코드를 확인하세요.", Toast.LENGTH_LONG).show();
		}else{
				startNetwork(SEARCH_CODE);
			}
			break;
		case R.id.MAIN_MEMBERSTUDENT_CONNECT_BTN:
			if (et.getText().length() == 0) {
				Toast.makeText(this, "자녀코드를 입력하세요.", Toast.LENGTH_LONG).show();
			} else{
				if (checkStudent != true) {
					Toast.makeText(this, "자녀코드확인을 눌러서 확인해주세요.", Toast.LENGTH_LONG).show();
				}else {
					startNetwork(INSERT_CODE);
				}
			}
			break;
		}
	}	
	
	@Override
	public void startThread(int choice) {
		super.startThread(choice);
		final int cho = choice;
		if(firstThread != null){firstThread.interrupt();}
		firstThread = new Thread(new Runnable() {
			@Override
			public void run() {
				switch (cho) {
				case SEARCH_CODE:		//자녀코드 확인.
					checkCode();
					break;
				case INSERT_CODE:		//자녀코드 입력.
					insertCode();
					break;
				}
			}
		});
		firstThread.start();
		startDIal();
	}	
	
	void checkCode(){	//자녀코드 확인.
		JSONObject jsonObject = null;
		try {
				jsonObject = new JSONObject(publicHttpCallback(HTTP_URL, 
						"code=" + CODE_MAIN_MEMBERSTUDENT_MATCHCHECK+
						"&PK_Mem_Email="+PK_Mem_Email+"&PK_Stu_Code="+et.getText().toString()));
				if (jsonObject.getBoolean("success")) {
					bc_Student_Che = JsonParser.Main_MemberStudent_Connect_Load(jsonObject.getString("payload"));
					onNetworkCallback(SEARCH_SUCCESS, "");
				} else {
					onNetworkCallback(SEARCH_FAILURE, jsonObject.getString("message"));
				}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString()+" where checkCode()");
		}	
	}	

	void insertCode(){	//자녀코드 입력.
		JSONObject jsonObject = null;
		try {
				jsonObject = new JSONObject(publicHttpCallback(HTTP_URL, 
						"code=" + CODE_MAIN_MEMBERSTUDENT_CONNECT+						
						"&PK_Mem_Email="+PK_Mem_Email+"&PK_Stu_Code="+et.getText().toString()));
				if (jsonObject.getBoolean("success")) {
					bc_Student_Che = JsonParser.Main_MemberStudent_Connect_Load(jsonObject.getString("payload"));
					onNetworkCallback(INSERT_SUCCESS, "");
				} else {
					onNetworkCallback(INSERT_FAILURE, jsonObject.getString("message"));
				}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION,e.toString()+" where insertCode()");
		}	
	}	
	
	@Override
	protected void handlingMessage(Message _message) {
		super.handlingMessage(_message);
		switch (_message.what){
		case SEARCH_SUCCESS:		//자녀검색 성공.
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}			
			dialog_Delete(1);
			break;
		case SEARCH_FAILURE:			//자녀검색 실패.
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}
			Toast.makeText(this, "자녀코드를 확인해주세요.", Toast.LENGTH_SHORT).show();
			break;
		case INSERT_SUCCESS:			//자녀등록 성공.
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}
			checkStudent = false;
			Toast.makeText(this,"자녀등록 성공", Toast.LENGTH_SHORT).show();
			setResult(REFRESH_CODE);
			startActivity(new Intent(Main_MemberStudent_Connect_A.this, Main_Intro.class));
			finish();
			break;
		case INSERT_FAILURE:			//자녀등록 실패.
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}
			checkStudent = false;
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT).show();
			break;
		case CATCH_EXCEPTION: // thread 에러 메세지
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}
			checkStudent = false;
			Toast.makeText(this, "자녀코드를 확인해 주세요.", Toast.LENGTH_SHORT).show();
			sqlite_Connect.insert_Err_Log((String)_message.obj,android.os.Build.VERSION.SDK_INT,"Main_MemberStudent_Connect_A", member.Email);
			break;
		}
	}
	
	// 네.아니오.선택다이얼로그
	void alertDialog(String string_title, int int_code) {
		final String title = string_title;
		final int code = int_code;
		AlertDialog.Builder builder = new AlertDialog.Builder(
				Main_MemberStudent_Connect_A.this);
		AlertDialog alert;
		builder.setMessage(title)
				.setCancelable(false)
				.setPositiveButton("네", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						startNetwork(code);
					}
				})
				.setNegativeButton("아니오",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.cancel();
							}
						});
		alert = builder.create();
		alert.show();
	}
	
	void dialog_Delete(final int pos1) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(bc_Student_Che.Stu_Name+"\n"+bc_Student_Che.schoolname+"\n"+bc_Student_Che.schoolclass+"\n생년월일:"+bc_Student_Che.Stu_Birth).setCancelable(false)
              .setPositiveButton("네", new DialogInterface.OnClickListener() {
                 @Override
                 public void onClick(DialogInterface dialog, int which) {
                	 checkStudent = true;
                     dialog.cancel();
                 }
              })
              .setNegativeButton("아니오", new DialogInterface.OnClickListener() {
                 @Override
                 public void onClick(DialogInterface dialog, int which) {
                	 et.setText("");
                    dialog.cancel();
                 }
              });
        AlertDialog alert = builder.create();
        alert.show();
     }   
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

////////////////

////////////////





}//CLASS_END
